import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:joyagoo/pages/widget/JoyProductHotCardWidget.dart';
import 'package:easy_refresh/easy_refresh.dart';

import '../config/app_colors.dart';
import '../model/productHotListModel.dart';
import '../utils/JoyBlocUtil.dart';
import '../utils/CountdownManager.dart';
import '../utils/currency_manager.dart';
import 'joy_home_bloc.dart';

//class JoyHotProductPage extends StatefulWidget{

class JoyHotProductPage extends StatefulWidget{

  final String title;


  JoyHotProductPage({
    this.title = "Best selling",
  });
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return JoyHotProductPageState();
  }

}
class JoyHotProductPageState extends State<JoyHotProductPage>{

  String error_acl = "No Data";
  bool isNetError_acl = false;
  String errorImage_acl = "";
  bool isError = false;
  List hotProductList = [];
  late JoyHomeBloc homeBloc;
  late EasyRefreshController _refreshController;
  int pageSize = 10;
  int pageNo = 1;
  
  // 货币变化监听器
  late CurrencyChangeListener _currencyChangeListener;


  @override
  void initState() {
    super.initState();
    _refreshController = EasyRefreshController(
        controlFinishRefresh: true, controlFinishLoad: true);
    
    // 初始化货币变化监听器
    _currencyChangeListener = (newCurrency, oldCurrency) {
      print('Hot product page: Currency changed from ${oldCurrency.code} to ${newCurrency.code}');
      // 货币改变时刷新热门商品页面数据
      _refreshHotProductData();
    };
    
    // 添加货币变化监听器
    CurrencyManager.instance.addListener(_currencyChangeListener);
  }

  @override
  void dispose() {
    // 移除货币变化监听器
    CurrencyManager.instance.removeListener(_currencyChangeListener);
    _refreshController.dispose();

    super.dispose();
  }

  // 刷新热门商品页面数据
  void _refreshHotProductData() {
    if (mounted) {
      // 重置页码
      pageNo = 1;
      // 清空当前列表
      hotProductList.clear();
      // 重新加载数据
      homeBloc.add(GetJOYHotProductListEvent(context, pageNo, pageSize, false));
      
      // 不显示重复提示，只刷新数据
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        Get.back();
        return false;
      },
      child: Scaffold(
          backgroundColor: AppColors.backgroundSecondary,
          appBar: _buildAppBar(),
          body: BLocMain()
      ),
    );
  }

  PreferredSizeWidget _buildAppBar() {
    return AppBar(
      elevation: 0,
      backgroundColor: Colors.transparent,
      flexibleSpace: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Color(0xFFFF6B35),
              Color(0xFFFF8E53),
            ],
          ),
        ),
      ),
      title: Text(
        widget.title,
        style: TextStyle(
          color: Colors.white,
          fontSize: 20.sp,
          fontWeight: FontWeight.bold,
          letterSpacing: 0.5,
        ),
      ),
      leading: GestureDetector(
        onTap: () => Get.back(),
        child: Container(
          margin: EdgeInsets.only(left: 10, right: 10, top: 10, bottom: 10),
          width: 40.w,
          height: 40.w,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(12.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.05),
                blurRadius: 8,
                offset: Offset(0, 2),
              ),
            ],
          ),
          child: Icon(
            Icons.arrow_back_ios_new,
            color: AppColors.primaryVariant,
            size: 18.sp,
          ),
        ),
      ),
      actions: [
        Container(
          margin: EdgeInsets.only(right: 16.w),
          child: Icon(
            Icons.local_fire_department,
            color: Colors.white,
            size: 24.sp,
          ),
        ),
      ],
    );
  }



  Widget BLocMain(){
    return JoyBlocUtil.getAppNoBarBloc(builder: (context, state) {
      return refrensh();
    }, create: (_) {

      homeBloc = JoyHomeBloc();
      homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,true));
      return homeBloc;
    }, buildWhen: (previousState, state) {

      if(state is GetJOYHotProductListEventSuccess){


        isNetError_acl = false; // 修改：成功时应该设置为false
        Map result  = state.data;
        debugPrint("GetALCHotProductListEventSuccess == $result");

        List productMap = result["records"]??[];
        debugPrint("GetALCHotProductListEventSuccess2 == $productMap");

        List hotProductListData = List<ProductHotModel>.from(productMap.map((x) => ProductHotModel.fromJson(x)));
        debugPrint("GetALCHotProductListEventSuccess2 == $hotProductList");

        debugPrint("=====${state.data}");
        if(pageNo == 1){
          hotProductList.clear();
          hotProductList.addAll(hotProductListData);
        }else{
          hotProductList.addAll(hotProductListData);
        }
        _refreshController.resetHeader();
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetFooter();

        if(hotProductListData.length < pageSize){
          _refreshController.finishLoad(IndicatorResult.noMore);
        }else{
          _refreshController.finishLoad();
        }

        if(hotProductList.isEmpty){
          error_acl = "No results found";
        }
        return true;
      }

      if(state is GetJOYHotProductListEventFailure){

        isNetError_acl = true;
        String message = state.errMsg??"Request failed";
        error_acl = message;
        pageNo = pageNo - 1;
        if(pageNo <= 0){
          pageNo = 1;
        }
        _refreshController.finishLoad();
        _refreshController.finishRefresh();
        _refreshController.resetHeader();
        _refreshController.resetFooter();

        return true;
      }

      return false;
    });
  }


  Widget refrensh() {
    return EasyRefresh(
        controller: _refreshController,
        onRefresh: (){
          loadData();
        },
        onLoad: (){
          moreData();
        },
        child: showMainBuild()
    );
  }

  void loadData(){
    pageNo = 1;
    homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));

  }
  void moreData(){
    pageNo = pageNo + 1;
    homeBloc.add(GetJOYHotProductListEvent(context,pageNo,pageSize,false));

  }
  Widget showMainBuild(){
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          end: Alignment.bottomCenter,
          colors: [
            Color(0xFFFF6B35).withOpacity(0.08),
            AppColors.backgroundSecondary,
            Colors.white
          ],
          stops: [0.0, 0.3, 1.0],
        ),
      ),
      child: _buildProductList(),
    );
  }


  Widget _buildProductList() {
    if (hotProductList.isEmpty) {
      return _buildEmptyState();
    }

    return _buildGridView();
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 120.w,
            height: 120.w,
            decoration: BoxDecoration(
              color: AppColors.backgroundSecondary,
              borderRadius: BorderRadius.circular(60.r),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withOpacity(0.05),
                  blurRadius: 20,
                  offset: Offset(0, 10),
                ),
              ],
            ),
            child: Icon(
              Icons.shopping_bag_outlined,
              size: 60.sp,
              color: AppColors.textHint,
            ),
          ),
          SizedBox(height: 24.h),
          Text(
            isNetError_acl ? error_acl : "No products available",
            style: TextStyle(
              fontSize: 18.sp,
              fontWeight: FontWeight.w600,
              color: AppColors.textSecondary,
            ),
          ),
          SizedBox(height: 8.h),
          Text(
            isNetError_acl ? "Please check your connection and try again" : "Check back later for new arrivals",
            style: TextStyle(
              fontSize: 14.sp,
              color: AppColors.textHint,
            ),
            textAlign: TextAlign.center,
          ),
          if (isNetError_acl) ...[
            SizedBox(height: 24.h),
            ElevatedButton(
              onPressed: () => loadData(),
              style: ElevatedButton.styleFrom(
                backgroundColor: Color(0xFFFF6B35),
                foregroundColor: Colors.white,
                padding: EdgeInsets.symmetric(horizontal: 32.w, vertical: 12.h),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(25.r),
                ),
                elevation: 2,
              ),
              child: Text(
                "Retry",
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          ],
        ],
      ),
    );
  }

  Widget _buildGridView() {
    return CustomScrollView(
      slivers: [
        // SliverPadding(
        //   padding: EdgeInsets.fromLTRB(16.w, 20.h, 16.w, 20.h),
        //   sliver: SliverToBoxAdapter(
        //     child: _buildHeader(),
        //   ),
        // ),
        SliverPadding(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          sliver: SliverGrid(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: 2,
              childAspectRatio: 0.6,
              crossAxisSpacing: 12.w,
              mainAxisSpacing: 16.h,
            ),
            delegate: SliverChildBuilderDelegate(
              (context, index) {
                ProductHotModel product = hotProductList[index];
                return AnimatedContainer(
                  duration: Duration(milliseconds: 300),
                  curve: Curves.easeInOut,
                  child: JoyProductHotCardWidget(
                    productModel: product,
                    onTap: () {
                      // 添加点击动画效果
                    },
                  ),
                );
              },
              childCount: hotProductList.length,
            ),
          ),
        ),
        SliverPadding(
          padding: EdgeInsets.only(bottom: 20.h),
        ),
      ],
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16.r),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 10,
            offset: Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        children: [
          Container(
            width: 4.w,
            height: 24.h,
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [Color(0xFFFF6B35), Color(0xFFFF8E53)],
              ),
              borderRadius: BorderRadius.circular(2.r),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  "🔥 Hot Products",
                  style: TextStyle(
                    fontSize: 18.sp,
                    fontWeight: FontWeight.bold,
                    color: AppColors.textPrimary,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  "${hotProductList.length} items found",
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: AppColors.textSecondary,
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 6.h),
            decoration: BoxDecoration(
              gradient: LinearGradient(
                colors: [Color(0xFFFF6B35), Color(0xFFFF8E53)],
              ),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: Text(
              "TRENDING",
              style: TextStyle(
                fontSize: 12.sp,
                fontWeight: FontWeight.bold,
                color: Colors.white,
                letterSpacing: 0.5,
              ),
            ),
          ),
        ],
      ),
    );
  }



}

